package com.asman.worker.rn

import androidx.fragment.app.FragmentActivity
import com.asman.worker.multishow.FileUtils
import com.asman.worker.utils.ImageDownloadUtils
import com.facebook.react.bridge.*
import java.util.*

/**
 * author : ybk
 * date   : 2019-10-22 10:32
 * desc   : 文件下载
 */
class NativeDownLoad(reactContext: ReactApplicationContext) :
    ReactContextBaseJavaModule(reactContext) {

    override fun getName(): String {
        return "NativeDownLoad"
    }

    override fun getConstants(): Map<String, Any>? {
        val constants = HashMap<String, Any>()
        return constants
    }

    /**
     * 下载文件或者图片到指定文件夹
     * @param downloadUrl 下载的url
     * @param folderName 下载到文件夹的名字
     * @param promise Promise 1：下载完成,-1：下载失败
     */
    @ReactMethod
    fun download(downloadUrl: String, folderName: String, promise: Promise) {
        if (currentActivity is FragmentActivity) {
            ImageDownloadUtils.newInstance(currentActivity as FragmentActivity)
                .startDownload(
                    downloadUrl,
                    folderName,
                    FileUtils.generatorLocalFileName(downloadUrl)
                ) {
                    promise.resolve(1)
                }
        } else {
            promise.resolve(-1)
        }
    }
}



